﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OnlineOrder.Entity
{
    internal class Utils
    {
        /*
     * ExecuteDataTable 方法用于执行查询语句并返回一个 DataTable 对象，可以用于获取查询结果的数据。
     * ExecuteNonQuery 方法用于执行非查询语句（如插入、更新、删除等）并返回受影响的行数。
     * ExecuteScalar 方法用于执行查询语句并返回结果集的第一行第一列的值。
     * using 语句块会在代码块执行完毕后自动调用连接对象的 Dispose 方法，从而释放相关资源。
     */
        public static class SqlHelper
        {
            private static readonly string ConnectionString = "Server=localhost;Database=OnlineOrder;User=sa;Password=123456;";

            public static DataTable ExecuteDataTable(string query, params SqlParameter[] parameters)
            {
                using (SqlConnection connection = new SqlConnection(ConnectionString))
                {
                    using (SqlCommand command = new SqlCommand(query, connection))
                    {
                        command.Parameters.AddRange(parameters);
                        using (SqlDataAdapter adapter = new SqlDataAdapter(command))
                        {
                            DataTable dataTable = new DataTable();
                            adapter.Fill(dataTable);
                            return dataTable;
                        }
                    }
                }
            }

            public static int ExecuteNonQuery(string query, params SqlParameter[] parameters)
            {
                using (SqlConnection connection = new SqlConnection(ConnectionString))
                {
                    using (SqlCommand command = new SqlCommand(query, connection))
                    {
                        command.Parameters.AddRange(parameters);
                        connection.Open();
                        return command.ExecuteNonQuery();
                    }
                }
            }

            public static object ExecuteScalar(string query, params SqlParameter[] parameters)
            {
                using (SqlConnection connection = new SqlConnection(ConnectionString))
                {
                    using (SqlCommand command = new SqlCommand(query, connection))
                    {
                        command.Parameters.AddRange(parameters);
                        connection.Open();
                        return command.ExecuteScalar();
                    }
                }
            }
        }
    }
}
